﻿using System;
using System.IO;

namespace com.fukefu.source
{
    public class SourceFormData
    {
        //函数
        Random random = new Random();
        MemoryStream ms = new MemoryStream();
        //变量
        string boundary = "";
        string bianma = "";
        bool endSign = true;

        public SourceFormData(string bianma)
        {
            boundary = "-----------------------------" + (random.Next(9000000) + 1000000) + (random.Next(9000000) + 1000000);
            this.bianma = bianma;
        }
        //写入一组数据
        public void Write(string name, string value)
        {
            WriteLine(boundary);
            WriteLine("Content-Disposition: form-data; name=\"" + name + "\"");
            WriteLine("");
            WriteLine(value);
        }
        //写入文件
        public void WriteFile(string name, string fileName)
        {
            WriteLine(boundary);
            WriteLine("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + (!string.IsNullOrEmpty(fileName) ? fileName.Substring(fileName.LastIndexOf(@"\") + 1) : "") + "\"");
            WriteLine("Content-Type: " + ContentType.GetContentType(fileName));
            WriteLine("");
            //文件内容
            if (!string.IsNullOrEmpty(fileName))
            {
                byte[] b = MyFunction.FileToBytes(fileName);
                ms.Write(b, 0, b.Length);
            }
            //结尾
            WriteLine("");
        }
        //读取数据
        public byte[] Read()
        {
            if (endSign)
            {
                WriteEndSign();
            }
            ms.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            return bytes;
        }
        //获取类型
        public string GetContentType()
        {
            return "multipart/form-data; boundary=" + boundary.Substring(2);
        }
        //写入结尾信号
        private void WriteEndSign()
        {
            WriteLine(boundary + "--");
            endSign = false;
        }
        //写入一行数据
        private void WriteLine(string mess)
        {
            Write(mess + "\r\n");
        }
        private void Write(string mess)
        {
            byte[] b = MyFunction.GetBytes(mess, bianma);
            ms.Write(b, 0, b.Length);
        }
    }
}
